package com.app.couponsharelife.ui.main.home.good

import android.annotation.SuppressLint
import android.content.*
import android.os.Build
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.AlibcTradeSDK
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.AlibcConstants
import com.alibaba.baichuan.trade.biz.context.AlibcResultType
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.alibaba.baichuan.trade.biz.login.AlibcLogin
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback
import com.bumptech.glide.manager.LifecycleListener
import com.google.gson.Gson
import com.hwangjr.rxbus.RxBus
//import com.kepler.jd.Listener.OpenAppAction
//import com.kepler.jd.login.KeplerApiManager
//import com.kepler.jd.sdk.bean.KeplerAttachParameter
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.databinding.ActivityGoodDetailBinding
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.GoodDetailAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.shopweb.ShopWebActivity
import com.app.couponsharelife.ui.main.home.shopweb.WebActivity
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.viewmodel.HomeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import com.app.fuquan.data.bean.PageStatus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_good_detail.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.jsoup.Jsoup
import java.lang.StringBuilder
import java.lang.ref.WeakReference
import java.text.DecimalFormat
import java.util.HashMap

class GoodDetailActivity : BaseActivity() {
    override val viewLayoutId: Int get() = R.layout.activity_good_detail
    private var myHandler:Handler?=null
    private var goodBean: TaobaoGoodBean? = null
    private val df = DecimalFormat("#0.00")
    //private var goodsType=""
    private var list = mutableListOf<Any>()
    private var listener: LifecycleListener? = null
    private var alibcShowParams: AlibcShowParams? = null//页面打开方式，默认，H5，Native
    private var exParams: HashMap<String, String>? = null//yhhpass参数
    private var alibcTaokeParams: AlibcTaokeParams? = null//淘客参数，包括pid，unionid，subPid
    private var mViewModel: HomeViewModel? = null
    //private var pddPromotionUrl=""  //拼多多推广链接打开App
    private var pddPromotionUrlOld=""  //拼多多推广链接无需打开App
    private var jdPromotionUrl=""  //京东推广链接
    private var jdSKUID=""  //京东商品ID
    private var isCollect = false
    private var goodsDetailsBean:PddGoodsDetailsBean?=null
    private var xlNumber=""
    private var wenAn=""
    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        myHandler=MyHandler(this)
        //goodsType=intent.getStringExtra("GoodsType")?:""
        if (intent!!.getSerializableExtra("good") != null) {
            goodBean = intent!!.getSerializableExtra("good") as TaobaoGoodBean
            xlNumber=goodBean!!.volume?:"0"
            wenAn=goodBean!!.goodsWenAn?:""
            if (goodBean!!.vip_commission!=null&&goodBean!!.vip_commission.isNotEmpty()) {
                tvShare.text = "分享赚￥${goodBean!!.vip_commission}"
                val price = df.format(goodBean!!.vip_commission.toDouble() + goodBean!!.coupon_price.toDouble())
                tvGetCoupon.text = "购买省￥$price"
            }
        }else {
            showToastMsg("数据错误，请重试")
            finish()
        }
        when(goodBean!!.goodsSource){
            "拼多多"->{
                //initData()
                initRecyclerView()
                getPddGoodsDetails()
            }
            "京东"->{
                initRecyclerView()
                if (goodBean!!.has_coupon){
                    getJDPromotionUrl()
                }else{
                    getJDWXPromotionUrl()
                }
            }
            else->{
                if (goodBean!!.goodsSource1=="好单库"){
                    val url="https://item.taobao.com/item.htm?id=${goodBean!!.item_id}"
                    getHDKGoods(url)
                }else {
                    initData()
                    initRecyclerView()
                }
            }
        }
        ivBack.setOnClickListener { onBackPressed() }
        initClickEvent()
    }

    @SuppressLint("CheckResult")
    private fun initData() {
        Observable.just(goodBean!!.num_iid as Any)
                .map {
                    val html = "https://api.m.taobao.com/h5/mtop.taobao.detail.getdesc/6.0/?appKey=${Contacts.APP_ID}&t=1526523633000&sign=cb1f63d319722e8be6da083a852c0137&api=mtop.taobao.detail.getdesc&v=6.0&type=jsonp&dataType=jsonp&timeout=20000&callback=mtopjsonp1&data={\"id\":\"${it}\",\"type\":\"0\",\"f\":\"TB1EyGIXUD\"}"
                    //println(html)
                    val res = Jsoup.connect(html).header("Accept", "*/*")
                            .header("Accept-Encoding", "gzip, deflate")
                            .header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                            .header("Content-Type", "application/json;charset=UTF-8")
                            .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
                            .timeout(10000).ignoreContentType(true).execute()
                    var body = res.body()
                    body = body.substring(11, body.length - 1)
                    //Log.e("error", body)
                    val goodDetailBean = Gson().fromJson(body, GoodDetailBean::class.java)
                    val sb = StringBuilder()
                    val list = mutableListOf<String>()
                    for (img in goodDetailBean!!.data.wdescContent.pages) {
                        //Log.e("error", img)
                        var start = img.indexOf("//")
                        var end = img.indexOf("jpg")
                        if (end == -1) {
                            end = img.indexOf("gif")
                        }
                        if (end == -1) {
                            end = img.indexOf("png")
                        }
                        if (start != -1 && end != -1) {
                            sb.append("<img src=\"http:").append(img.substring(start, img.length - 6)).append("\"/>")
                            list.add("http:" + img.substring(start, img.length - 6))
                        } else {
                            if (img.contains("<img>") && img.contains("</img>")) {
                                start = img.indexOf("<img>")
                                end = img.indexOf("</img>")
                                sb.append("<img src=\"http:").append(img.substring(start + 5, end)).append("\"/>")
                                list.add("http:" + img.substring(start + 5, end))
                            } else
                                sb.append(img)
                        }
                    }
                    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1)
                        list
                    else
                        sb.toString()
                }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it is MutableList<*>) {
                        list.clear()
                        list.add(goodBean as Any)
                        list.add(HtmlBean(""))
                        list.addAll(it as Collection<Any>)
                    } else {
                        list.clear()
                        list.add(goodBean as Any)
                        list.add(HtmlBean(it as String))
                    }
                    (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
                }, {
                    Log.e("error", it.message)
                    list.clear()
                    list.add(goodBean as Any)
                    (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
                })
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        mRecyclerView.adapter = GoodDetailAdapter(arrayListOf(PageTipBean("", 0, 0)), this, object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                if (arg2=="GetCoupon"){
                    if (AppUtils.checkUserLogin())  // && judgeAdzoneIdExist()
                        //goTaoBao()
                        startIntent()
                    else
                        //startActivity(Intent(this@GoodDetailActivity, LoginActivity::class.java))
                        startActivity(Intent(this@GoodDetailActivity, NewLoginActivity::class.java))
                }
                if (arg1==100){
                    if (arg2!=null){
                        val content=arg2 as String
                        if (content!=null&&content.isNotEmpty()){
                            copyContent(content.trimStart().trimEnd())
                        }
                    }
                }
            }
        })
    }

    private fun initClickEvent() {
        (mViewDataBinding as ActivityGoodDetailBinding).listener = View.OnClickListener {
            when (it.id) {
                R.id.clCollect -> {
                    if (AppUtils.checkUserLogin()) // && judgeAdzoneIdExist()
                        goCollect()
                    else
                        //startActivity(Intent(this@GoodDetailActivity, LoginActivity::class.java))
                        startActivity(Intent(this@GoodDetailActivity, NewLoginActivity::class.java))
                }
                R.id.clShare -> {
                    if (AppUtils.checkUserLogin())  // && judgeAdzoneIdExist()
                        goShare()
                    else
                        //startActivity(Intent(this@GoodDetailActivity, LoginActivity::class.java))
                        startActivity(Intent(this@GoodDetailActivity, NewLoginActivity::class.java))
                }
                R.id.clGetCoupon -> {
                    if (AppUtils.checkUserLogin())  // && judgeAdzoneIdExist()
                        //goTaoBao()
                        startIntent()
                    else
                        //startActivity(Intent(this@GoodDetailActivity, LoginActivity::class.java))
                        startActivity(Intent(this@GoodDetailActivity, NewLoginActivity::class.java))
                }
            }
        }
    }
    private fun setJDData(){
        list.clear()
        list.add(goodBean as Any)
        list.add(goodBean!!.images[0])
        (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
    }
    private fun startIntent(){
        var intent:Intent?=null
        when(goodBean!!.goodsSource){
            "拼多多"->{
                intent= Intent(this,ShopWebActivity::class.java)
                intent.putExtra("url", pddPromotionUrlOld)
                //intent.putExtra("urlold", pddPromotionUrlOld)
                intent.putExtra("name", "拼多多")
                startActivity(intent)
            }
            "京东"->{
                startJD()
            }
            else->{
                val rlID=AppUtils.getString(Contacts.ADZONE_ID, "")
                if (rlID.isNotEmpty()){
                    goTaoBao()
                }else{
                    //getAliLoginUrl()
                    taobaoLogin()
                }
                //goTaoBao()
            }
        }
    }

    private fun goShare() {
        if ("京东"==goodBean!!.goodsSource||"拼多多"==goodBean!!.goodsSource){
            if (goodBean!!.pict_url !is String || (goodBean!!.pict_url as String) == "") {
                //Log.e("eee","---->"+goodBean!!.pict_url)
                showToastMsg("该商品暂时不支持分享")
                return
            }
            val intent = Intent(this, GoodShareActivity::class.java)
            intent.putExtra("good", goodBean)
            startActivity(intent)
        }else{
            val rlID=AppUtils.getString(Contacts.ADZONE_ID, "")
            if (rlID.isNotEmpty()){
                if (goodBean!!.pict_url !is String || (goodBean!!.pict_url as String) == "") {
                    //Log.e("eee","---->"+goodBean!!.pict_url)
                    showToastMsg("该商品暂时不支持分享")
                    return
                }
                val intent = Intent(this, GoodShareActivity::class.java)
                intent.putExtra("good", goodBean)
                startActivity(intent)
            }else{
                //getAliLoginUrl()
                taobaoLogin()
            }
        }
    }
    private fun copyContent(content: String) {
        //获取剪贴板管理器：
        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", content)
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg("商品标题复制成功")
    }
    private fun goTaoBao() {
        showCountDownProgressDialog("请稍候", 3)
        alibcShowParams = AlibcShowParams(OpenType.Native, false)
        exParams = HashMap()
        exParams!![AlibcConstants.ISV_CODE] = "appisvcode"
        exParams!!["alibaba"] = "阿里巴巴"//自定义参数部分，可任意增删改
        // 若非淘客taokeParams设置为null即可
        val pid = Contacts.ALIMAMA_PID //+ AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams = AlibcTaokeParams()
        alibcTaokeParams?.adzoneid = "65231850041"//AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams?.pid = pid
        alibcTaokeParams?.subPid = pid
        alibcTaokeParams?.extraParams = HashMap()
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["taokeAppkey"] = Contacts.APP_ID
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["relationId"] = AppUtils.getString(Contacts.ADZONE_ID, "")
        val url = if (goodBean!!.coupon_share_url_new != "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }
        if (url == "") {
            showToastMsg("该商品暂时不能购买")
            return
        }
        AlibcTrade.show(this, AlibcPage(url+"&relationId=${AppUtils.getString(Contacts.ADZONE_ID, "")}"), alibcShowParams, alibcTaokeParams, exParams, object : AlibcTradeCallback {
            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
                //当addCartPage加购成功和其他page支付成功的时候会回调
                if (tradeResult.resultType == AlibcResultType.TYPECART) {
                    //加购成功
                    showToastMsg("加购成功")
                } else if (tradeResult.resultType == AlibcResultType.TYPEPAY) {
                    //支付成功
//                    Log.d("order", tradeResult.payResult.paySuccessOrders[0])
                }
            }

            override fun onFailure(errCode: Int, errMsg: String) {
                showToastMsg("电商SDK出错,错误码=$errCode / 错误消息=$errMsg")
            }
        })
    }

    fun registerLifeListener(listener: LifecycleListener) {
        this.listener = listener
        this.listener?.onStart()
    }

    override fun onDestroy() {
        AlibcTradeSDK.destory()
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }

    private fun goCollect() {
        var url = if (goodBean!!.coupon_share_url_new != "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }
        val map = HashMap<String, String>()
        map["numIid"] = goodBean!!.num_iid
        if (!isCollect) {
            map["title"] = goodBean!!.title
            map["pictUrl"] = if (goodBean!!.pict_url is String) goodBean!!.pict_url as String else ""
            map["smallImages"] = getSmallImages()//if (goodBean!!.small_images != null) goodBean!!.small_images.toString() else ""
            map["reservePrice"] = goodBean!!.original_price
            map["zkFinalPrice"] = goodBean!!.final_price
            map["itemUrl"] = goodBean!!.item_url
            map["commissionRate"] = goodBean!!.commission_rate
            map["volume"] = goodBean!!.volume
            map["couponRemainCount"] = goodBean!!.coupon_remain_count
            map["couponInfo"] = goodBean!!.coupon_price
            val type=when(goodBean!!.goodsSource){
                "拼多多"->{
                    url=pddPromotionUrlOld
                    "3"
                }
                "京东"->{
                    url=goodBean!!.url
                    "4"
                }
                "淘宝"->{
                    "0"
                }
                "天猫"->{
                    "1"
                }
                else->{
                    "0"
                }
            }
            map["clickUrl"] = url
            map["platformType"] = type
            map["couponStartTime"] = goodBean!!.coupon_start_time
            map["couponEndTime"] = goodBean!!.coupon_end_time
            if (url == "") {
                showToastMsg("该商品暂时不能收藏")
                return
            }
        }
        map["isAdd"] = "${!isCollect}"
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshAddCollect(map, true)
    }
    //转换平台轮播图
    private fun getSmallImages():String{
        var imagurl=""
        if (goodBean!!.images.isNotEmpty()){
            for (url in goodBean!!.images){
                imagurl+="$url,"
            }
            imagurl=imagurl.substring(0,imagurl.length-1)
        }
        //Log.e("eee","--->$imagurl")
        return imagurl
    }
    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
        if (!mViewModel!!.addCollect()!!.hasObservers()) {
            mViewModel!!.addCollect()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddCollect(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddCollect(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddCollect(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            if (!isCollect)
                                ivCollect.setImageResource(R.drawable.ic_act_good_detail_collect_true)
                            else
                                ivCollect.setImageResource(R.drawable.ic_act_good_detail_collect)
                            if (isCollect)
                                showToastMsg("取消收藏成功")
                            else
                                showToastMsg("收藏成功")
                            isCollect = !isCollect
                        } else {
                            if (isCollect)
                                showToastMsg("取消收藏失败")
                            else
                                showToastMsg("收藏失败")
                        }
                    }
                }
            })
            mViewModel!!.isGoodCollect()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshIsGoodCollect(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshIsGoodCollect(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshIsGoodCollect(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            if (it.data.data!! as Boolean) {
                                isCollect = true
                                ivCollect.setImageResource(R.drawable.ic_act_good_detail_collect_true)
                            } else
                                ivCollect.setImageResource(R.drawable.ic_act_good_detail_collect)
                        } else {
                            ivCollect.setImageResource(R.drawable.ic_act_good_detail_collect)
                        }
                    }
                }
            })
        }
        isGoodCollect()
    }
    private fun getAliLoginUrl(){
        showProgressDialog("加载中...")
        val map = HashMap<String, String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getAuthUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            val url=it.data?:""
                            if (url.isNotEmpty()){
                                val intent= Intent(this@GoodDetailActivity, WebActivity::class.java)
                                intent.putExtra("url", url)
                                intent.putExtra("name", "淘宝授权")
                                startActivity(intent)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){
                                goTaoBao()
                            }
                        }
                    }
                })
    }
    private fun isGoodCollect() {
        if (goodBean != null && goodBean!!.num_iid != "") {
            val map = HashMap<String, String>()
            map["userId"] = AppUtils.getString(Contacts.USERID, "")
            map["numIid"] = goodBean?.num_iid!!
            mViewModel?.freshIsGoodCollect(map, true)
        }
    }
    private fun getPddGoodsDetails(){
        showProgressDialog("请稍后...")
        val map = HashMap<String, String>()
        map["id"] = goodBean!!.num_iid
        RetrofitWorker.retrofitWorker.getPDDGoodsDetails(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<List<PddGoodsDetailsBean>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<PddGoodsDetailsBean>>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            if (it.data!=null&&it.data!!.isNotEmpty()){
                                goodsDetailsBean=it.data!![0]
                                val list= arrayListOf<String>()
                                val imagList=goodsDetailsBean!!.goods_gallery_urls!!
                                imagList.forEach {
                                    list.add(it)
                                }
                                getPDDPromotionUrl(imagList)
                            }else{
                                list.clear()
                                goodBean!!.images.add("")
                                list.add(goodBean as Any)
                                (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        list.clear()
                        goodBean!!.images.add("")
                        list.add(goodBean as Any)
                        (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun getPDDPromotionUrl(imagList:List<String>){
        val map=HashMap<String,String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["goodsId"]=goodBean!!.num_iid
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.getPDDPromotionUrl(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<PDDPromotionUrlBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<PDDPromotionUrlBean>) {
                        if (it.code==200){
                            if (it.data!=null&&it.data!!.goods_promotion_url_list!=null&&it.data!!.goods_promotion_url_list!!.isNotEmpty()){
                                val goodsPromotionUrl=it.data!!.goods_promotion_url_list!![0]
                                //pddPromotionUrl=goodsPromotionUrl.mobile_url!!
                                pddPromotionUrlOld=goodsPromotionUrl.url!!
                                goodBean!!.coupon_share_url=pddPromotionUrlOld
                            }
                            list.clear()
                            list.add(goodBean as Any)
                            for (i in 0 until imagList.size){
                                if (i==0){
                                    goodBean!!.images.add(imagList[i])
                                }else{
                                    list.add(imagList[i])
                                }
                            }
                            (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
                        }else{
                            list.clear()
                            goodBean!!.images.add("")
                            list.add(goodBean as Any)
                            (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
                        }
                    }

                    override fun onError(e: Throwable) {
                        list.clear()
                        goodBean!!.images.add("")
                        list.add(goodBean as Any)
                        (mRecyclerView.adapter as GoodDetailAdapter).setData(list)
                    }

                })
    }
    private fun getJDPromotionUrl(){
        showProgressDialog("加载中...")
        jdSKUID=goodBean!!.num_iid?:""
        val map=HashMap<String,String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["materialids"]=goodBean!!.num_iid
        map["couponurl"]=goodBean!!.url
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.getJDCouponlink(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            jdPromotionUrl=it.data!!
                            goodBean!!.coupon_share_url=jdPromotionUrl
                            setJDData()
                        }else{
                            setJDData()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        setJDData()
                    }

                })
    }
    private fun getJDWXPromotionUrl(){
        showProgressDialog("加载中...")
        val map=HashMap<String,String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["materialids"]=goodBean!!.num_iid
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.getJDWXCouponlink(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            jdPromotionUrl=it.data!!
                            goodBean!!.coupon_share_url=jdPromotionUrl
                            setJDData()
                        }else{
                            setJDData()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        setJDData()
                    }

                })
    }
    private fun getHDKGoods(keyword:String){
        val map=HashMap<String,String>()
        map["pageNo"]="1"
        map["pageSize"]="1"
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        map["keyword"]=keyword
        RetrofitWorker.retrofitWorker.getTBGoodsList(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoSearchData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<SearchTBGoodsListBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<SearchTBGoodsListBean>) {
                        if (it.data!=null&&it.data!!.recordss.isNotEmpty()){
                            val taobaoGoodBean=it.data!!.recordss[0]
                            for (i in it.data!!.records.asReversed())
                            if (xlNumber!="0"){
                                taobaoGoodBean.volume=xlNumber
                            }
                            taobaoGoodBean.goodsWenAn=wenAn
                            goodBean=taobaoGoodBean
                            tvShare.text="分享赚￥${goodBean!!.vip_commission}"
                            val price=df.format(goodBean!!.vip_commission.toDouble()+goodBean!!.coupon_price.toDouble())
                            tvGetCoupon.text="购买省￥$price"
                            initData()
                            initRecyclerView()
                            //setGoodsDialog(keyword,taobaoGoodBean)
                        }else{
                            showToastMsg("该商品已下架！")
                            finish()
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            Log.e("eee","---->"+e.toString())
                            //showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun startJD(){
//        val key= KeplerAttachParameter()
//        val mOpenAppAction= object : OpenAppAction {
//            override fun onStatus(status: Int) {
//                myHandler!!.post {
//                    if (status == OpenAppAction.OpenAppAction_start) {//开始状态未必一定执行，
//
//                    } else {
//
//                    }
//                }
//            }
//        }
//        if (jdPromotionUrl.isNotEmpty()){
//            KeplerApiManager.getWebViewService().openJDUrlPage(jdPromotionUrl,key,this,mOpenAppAction,15)
//        }else{
//            KeplerApiManager.getWebViewService().openItemDetailsPage(jdSKUID,key,this,mOpenAppAction,15)
//        }
    }
    private class MyHandler(activity: GoodDetailActivity) : Handler() {
        private val mActivity: WeakReference<GoodDetailActivity> = WeakReference<GoodDetailActivity>(activity)
        private var activity:GoodDetailActivity?=null
        override fun handleMessage(msg: Message) {
            if (activity== null) {
                activity=mActivity.get()
            }
            when (msg.what) {
                0 -> {

                }
                else -> {

                }
            }
        }
    }
    private fun taobaoLogin(){
        showProgressDialog("请稍后")
        val alibcLogin = AlibcLogin.getInstance()
        alibcLogin.showLogin(object : AlibcLoginCallback{
            override fun onSuccess(p0: Int) {
                //showToastMsg("登录成功 ")
                //获取淘宝用户信息
                //Log.i("eee", "获取淘宝用户信息: "+AlibcLogin.getInstance().session)
                dismissProgressDialog()
                getAliLoginUrl()
            }

            override fun onFailure(p0: Int, p1: String?) {
                //showToastMsg("登录失败")
                dismissProgressDialog()
            }
        })
    }
    override fun onBackPressed() {
        if (!isCollect) {
            RxBus.get().post("freshCancelCollect", "")
        }
        super.onBackPressed()
    }
}
